//
//  XLGDownloadPool.m
//  etionCBLogic
//
//  Created by wjxfhxy on 15-8-19.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XLGDownloadPool.h"

#import "XLGDownloadOperation.h"

#import "XLGDownloadPoolItem+XLGDownloadPoolInternal.h"

@implementation XLGDownloadPoolItem

- (void)dealloc
{
    superdealloc_mm;
}

@end



@interface XLGDownloadPool ()<XLGDownloadPoolDelegate>
{
    NSLock *_lock;
    NSMutableArray *_pool;
    NSUInteger _maxCount;
}
@end

@implementation XLGDownloadPool

@synthesize maxCount = _maxCount;

- (id)init
{
    self = [super init];
    
    _lock = [NSLock new];
    
    _pool = [NSMutableArray new];
    
    _maxCount = 2;
    
    return self;
}

- (void)dealloc
{
    [_lock release_mm];
    [_pool release_mm];
    superdealloc_mm;
}

- (BOOL)addDownloadOperation:(XLGDownloadPoolItem *)downloadOperation
{
    __block BOOL b = NO;
    
    [_lock lock:^
    {
        if(_pool.count >= _maxCount)
        {
            b = NO;
        }
        else
        {
            b = YES;
            
            downloadOperation.poolDelegate = self;
            
            [_pool addObject:downloadOperation];
        }
    }];
    
    if(b == YES)
    {
        b = [downloadOperation startItem];
        if(b != YES)
        {
            [downloadOperation stopItem];
        }
    }
    
    return b;
}

- (void)removeDownloadOperation:(XLGDownloadPoolItem *)downloadOperation
{
    downloadOperation.poolDelegate = nil;
    
    [_lock lock:^
    {
        [_pool removeObject:downloadOperation];
    }];
}

- (NSUInteger)currentCount
{
    __block NSUInteger count = 0;
    [_lock lock:^
    {
        count = _pool.count;
    }];
    return count;
}

@end

@implementation XLGDownloadPool(XLGDownloadOperation)

- (void)enumDownloadOperation:(void(^)(XLGDownloadOperation *operation,NSUInteger idx,BOOL *stop))block
{
    [_lock lock:^
    {
        [_pool enumerateObjectsUsingBlock:block];
    }];
}

- (XLGDownloadOperation*)findDownloadOperationWithDownloadIndex:(XLGDownloadIndex*)dli
{
    __block XLGDownloadOperation *o = nil;
    [self enumDownloadOperation:^(XLGDownloadOperation *operation, NSUInteger idx, BOOL *stop)
    {
        if([operation.mi.extendID isEqualToString:dli.extendID])
        {
            o = operation;
            *stop = YES;
        }
    }];
    return [[o retain_mm] autorelease_mm];
}

@end

